from typing import List, Optional
from fastapi import APIRouter, Depends, Path, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field

from app.models import get_db
from app.services.role_service import RoleService
from app.utils.response import Response
from app.utils.pagination import BasePage

router = APIRouter(prefix="/roles", tags=["角色管理"])

# 请求模型
class RoleCreate(BaseModel):
    """角色创建请求模型"""
    name: str = Field(..., description="角色名称", example="admin")
    code: str = Field(..., description="角色编码", example="ROLE_ADMIN")
    description: Optional[str] = Field(None, description="角色描述", example="系统管理员")

class RoleUpdate(BaseModel):
    """角色更新请求模型"""
    name: Optional[str] = Field(None, description="角色名称", example="admin")
    code: Optional[str] = Field(None, description="角色编码", example="ROLE_ADMIN")
    description: Optional[str] = Field(None, description="角色描述", example="系统管理员")

# 响应模型
class RoleOut(BaseModel):
    """角色返回模型"""
    id: int
    name: str
    code: str
    description: Optional[str] = None
    
    class Config:
        from_attributes = True

class UserRoleAssign(BaseModel):
    """用户角色分配请求模型"""
    user_id: int = Field(..., description="用户ID", example=1)
    role_id: int = Field(..., description="角色ID", example=1)

# API接口
@router.post("", response_model=dict)
def create_role(role: RoleCreate, db: Session = Depends(get_db)):
    """创建角色"""
    new_role = RoleService.create_role(
        db,
        name=role.name,
        code=role.code,
        description=role.description
    )
    return Response.success(RoleOut.model_validate(new_role))

@router.get("/{role_id}", response_model=dict)
def get_role(role_id: int = Path(..., description="角色ID"), db: Session = Depends(get_db)):
    """获取单个角色"""
    role = RoleService.get_role_by_id(db, role_id)
    return Response.success(RoleOut.model_validate(role))

@router.get("", response_model=dict)
def get_role_list(
    page_params: BasePage = Depends(),
    db: Session = Depends(get_db)
):
    """获取角色列表"""
    result = RoleService.get_role_list(db, page_params.page, page_params.page_size)
    result['items'] = [RoleOut.model_validate(role) for role in result['items']]
    return Response.page_success(data=result['items'], total=result['total'])

@router.put("/{role_id}", response_model=dict)
def update_role(
    role_update: RoleUpdate,
    role_id: int = Path(..., description="角色ID"),
    db: Session = Depends(get_db)
):
    """更新角色"""
    role = RoleService.update_role(db, role_id, **role_update.model_dump(exclude_unset=True))
    return Response.success(RoleOut.model_validate(role))

@router.delete("/{role_id}", response_model=dict)
def delete_role(role_id: int = Path(..., description="角色ID"), db: Session = Depends(get_db)):
    """删除角色"""
    RoleService.delete_role(db, role_id)
    return Response.success(data={"message": f"角色 {role_id} 已删除"})

@router.post("/assign", response_model=dict)
def assign_role_to_user(assign_data: UserRoleAssign, db: Session = Depends(get_db)):
    """给用户分配角色"""
    user = RoleService.assign_role_to_user(db, assign_data.user_id, assign_data.role_id)
    return Response.success(data={"message": f"已成功为用户 {assign_data.user_id} 分配角色 {assign_data.role_id}"})

@router.post("/remove", response_model=dict)
def remove_role_from_user(assign_data: UserRoleAssign, db: Session = Depends(get_db)):
    """从用户中移除角色"""
    user = RoleService.remove_role_from_user(db, assign_data.user_id, assign_data.role_id)
    return Response.success(data={"message": f"已成功从用户 {assign_data.user_id} 移除角色 {assign_data.role_id}"})

@router.get("/user/{user_id}", response_model=dict)
def get_user_roles(user_id: int = Path(..., description="用户ID"), db: Session = Depends(get_db)):
    """获取用户的所有角色"""
    roles = RoleService.get_user_roles(db, user_id)
    return Response.success(data=[RoleOut.model_validate(role) for role in roles])
